package com.simtop.security;

import com.simtop.domain.user.SysUser;
import com.simtop.service.SysUserService;
import com.simtop.service.impl.SysPermissionService;
import com.simtop.utils.ifnull.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Set;

/**
 * @ClassName UserServiceImpl
 * @Description TODO
 * @Author lvyongwei
 * @Date 2020-08-17 17:45
 **/
@Service
public class UserServiceImpl implements UserDetailsService {

    @Autowired
    private static final Logger logger= LoggerFactory.getLogger(UserServiceImpl.class);

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private SysPermissionService sysPermissionService;

    @Override
    public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
        SysUser user = sysUserService.getUserByUserName(userName);
        if (StringUtils.isNull(user))
        {
            logger.info("登录用户：{} 不存在.", userName);
            throw new UsernameNotFoundException("登录用户：" + userName + " 不存在");
        }
        else if (user.getDelStatus() == 1)
        {
            logger.info("登录用户：{} 已被删除.", userName);
            throw new RuntimeException("对不起，您的账号：" + userName + " 已被删除");
        }
        else if (user.getDelStatus() == 2) {
            logger.info("登录用户：{} 已被停用.", userName);
            throw new RuntimeException("对不起，您的账号：" + userName + " 已停用");
        }
        /**
         * 获取权限信息
         */
        Set<String> permission=sysPermissionService.getMenuPermission(user);
        User user1=new User(permission,user);
        return user1;
    }
}
